package com.hutu.service.biz.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.hutu.constances.Constance;
import com.hutu.mapper.biz.ModuleMapper;
import com.hutu.model.biz.Column;
import com.hutu.model.biz.Module;
import com.hutu.model.biz.TableInfo;
import com.hutu.model.resp.Response;
import com.hutu.model.resp.ResponseVo;
import com.hutu.service.biz.ColumnService;
import com.hutu.service.biz.PublicVarsService;
import com.hutu.service.biz.TableInfoService;
import com.hutu.util.CommonUtil;
import com.hutu.util.JWTUtil;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.VelocityEngine;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringWriter;
import java.net.URLEncoder;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hutu.service.biz.ModuleService;

/**
 * <p>
 * 表信息 服务类
 * </p>
 *
 * @author admin
 * @since 2023-07-19
 */
@Service
public class  ModuleServiceImpl extends ServiceImpl<ModuleMapper,Module > implements ModuleService{

    @Resource
    private PublicVarsService publicVarsService;

    @Resource
    private ColumnService columnService;

    @Resource
    TableInfoService tableInfoService;


    public ResponseVo add(Module module){
        if(save(module)){
            return Response.success();
        }
        return Response.error();
    }

    public ResponseVo deleteById(Integer id){
        if(removeById(id)){
            return Response.success();
        }
        return Response.error();
    }

    public ResponseVo deleteBatch(List<Integer> ids){
        if(removeBatchByIds(ids)){
            return Response.success();
        }
        return Response.error();
    }


    public ResponseVo edit(Module module){
        if(updateById(module)){
            return Response.success();
        }
        return Response.error();
    }


    public ResponseVo findById(Integer id){
        Module module =getById(id);
        if(module !=null){
            return Response.success(module);
        }
        return Response.error();
    }


    public ResponseVo list(Integer current,Integer size,String projectId){
        IPage<Module> config=new Page<>(current,size);
        QueryWrapper<Module> wrapper=new QueryWrapper<>();;
        if(StrUtil.isNotBlank(projectId)){
            wrapper.like("project_id",projectId);
        }

        wrapper.select("id,name,project_id,content,create_user_name,type," +
                "(select table_name from base_project where id = ht_module.project_id) projectName");

        IPage<Module> page=page(config,wrapper);
        // 将响应数据填充到map中
        Map map=new HashMap();
        map.put("pages",page.getPages());
        map.put("total",page.getTotal());
        map.put("list",page.getRecords());
        return Response.success(map);
    }

    @Override
    public Module findByProject(String project, String type) {
        return baseMapper.selectOne(new LambdaQueryWrapper<Module>().eq(Module::getProjectId,project).eq(Module::getType,type));
    }

    @Override
    public ResponseVo getCommonList(String projectId) {
        LambdaQueryWrapper<Module> moduleLambdaQueryWrapper = new LambdaQueryWrapper<>();
        moduleLambdaQueryWrapper.eq(Module::getProjectId,projectId);
        moduleLambdaQueryWrapper.eq(Module::getType,"默认");
        return Response.success(baseMapper.selectList(moduleLambdaQueryWrapper));
    }

    @Override
    public ResponseVo createCommonModule(String moduleId, String fields) {
        String[] split = fields.split(",");
        List<String> fieldList = Arrays.asList(split);
        List<Integer> integerList = fieldList.stream()
                .map(s -> {
                    try {
                        return Integer.parseInt(s);
                    } catch (NumberFormatException e) {
                        // 这里可以抛出异常、记录日志或返回null/默认值
                        throw new RuntimeException(e); // 示例中直接抛出运行时异常
                    }
                }).collect(Collectors.toList());
        List<Column> columns = columnService.findByIds(integerList);

        Integer tableId = columns.get(0).getTableId();

        TableInfo tableInfo = (TableInfo)tableInfoService.findById(tableId).getData();
        String remark = tableInfo.getRemark();
        String tableNameUnder = tableInfo.getTableName();
        String tableNameNoUnder = CommonUtil.transformUnderscoreToCamelCase(tableNameUnder);

        com.hutu.entity.system.Staff staff = JWTUtil.currentUser.get();


        Module module = getById(moduleId);
        String template = module.getContent();
        VelocityContext context = new VelocityContext();
        // 注入参数
        context.put("author", staff.getName());     //作者
        context.put("date", DateUtil.now());        //日期
        context.put("tableName",remark );           //表中文,比如学生信息
        context.put("tableNameUnder",tableNameUnder );    //原始表名，比如 t_student
        context.put("tableNameNoUnder",CommonUtil.firstUpper(tableNameNoUnder) ); //表英文，比如 Student
        context.put("fields", columns); //表字段
        context.put("packageName", tableInfo.getPackageName());
        //java类型转换
        columns.forEach(e -> {
            e.setColumnType(CommonUtil.transferJdbcType2java(e.getColumnType()));
            e.setColumnName(CommonUtil.transferCamel(e.getColumnName()));
        });

        // 注入参数
        context.put("tableFields", columns);

        StringWriter writer = new StringWriter();
        VelocityEngine engine = new VelocityEngine();
        engine.init();
        engine.evaluate(context, writer, "velocity", template);
        String result = writer.toString();
        ResponseVo vo = new ResponseVo();
        vo.setData(result);
        return Response.success(vo);
    }

    /**
    * 数据导出
    *
    * @param response
    * @return
    */
    public ResponseVo export(HttpServletResponse response)throws IOException{
        List<Module> list=list();
        // 通过工具类创建对象，可以指定磁盘路径
        ExcelWriter writer=ExcelUtil.getWriter(true);
        // 一次性将list内的数据写入到excel，使用默认样式,强制输出标题
        writer.write(list,true);
        // 设置浏览器响应的格式
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
        String filename=URLEncoder.encode("数据","UTF-8");
        response.setHeader("Content-Disposition","attachment;filename="+filename+".xlsx");
        ServletOutputStream outputStream=response.getOutputStream();
        writer.flush(outputStream,true);
        outputStream.close();
        writer.close();
        return Response.success();
    }

    /**
     * 数据导入
     *
     * @param file
     * @return
     */
    public ResponseVo imp(MultipartFile file)throws IOException{
        InputStream inputStream=file.getInputStream();
        ExcelReader reader=ExcelUtil.getReader(inputStream);
        List<Module> list=reader.readAll(Module.class);
        // IService接口中的方法.批量插入数据
        if(saveBatch(list)){
            return Response.success();
        }
        return Response.error();
    }


}




